package com.qc31.monitorlib.ui.carsmonitor

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.location.Location
import android.net.Uri
import android.view.Gravity
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.collection.LruCache
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.*
import com.gyf.immersionbar.ktx.immersionBar
import com.qc31.monitorlib.ui.popup.CarsPopup
import com.qc31.baselib.rx.LiveDataBus
import com.qc31.baselib.rx.clickThrottle
import com.qc31.baselib.utils.*
import com.qc31.baselib.utils.ActivityResultUtil.launchAct
import com.qc31.baselib.utils.ActivityResultUtil.registerResult
import com.qc31.comlib.Keys
import com.qc31.comlib.NetDataUtil
import com.qc31.comlib.UserConstant
import com.qc31.comlib.choose.team.ChooseTeamActivity
import com.qc31.comlib.entity.GpsDetail
import com.qc31.comlib.map.MarkerSet
import com.qc31.monitorlib.ui.popup.MapTimePopup
import com.qc31.monitorlib.ui.popup.ChooseNaviPopup
import com.qc31.monitorlib.R
import com.qc31.monitorlib.base.BaseMapLocationActivity
import com.qc31.monitorlib.clusters.*
import com.qc31.monitorlib.databinding.ActivityMonitorCarsBinding
import com.qc31.monitorlib.databinding.IncludeCarMapInfoBinding
import com.qc31.monitorlib.databinding.IncludeCarOperaBinding
import com.qc31.monitorlib.login.LocationStatusModel
import com.qc31.monitorlib.ui.adapter.CarInfoAdapter
import com.qc31.monitorlib.ui.carinfo.CarInfoActivity
import com.qc31.monitorlib.ui.line.HistoryLineActivity
import com.qc31.monitorlib.ui.other.InfoSetActivity
import com.qc31.monitorlib.ui.photo.PhotosActivity
import com.qc31.monitorlib.ui.popup.LegendPopup
import com.qc31.monitorlib.ui.popup.MapMorePopup
import com.qc31.monitorlib.ui.singlemap.SingleMonitorActivity
import com.qc31.monitorlib.ui.video.RealVideoActivity
import com.qc31.monitorlib.uitls.ColorUtil
import com.qc31.monitorlib.uitls.MapUtil
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/** @author joker @date 2022/8/1$ 10:20$ */
class MultiMonitorActivity :
    BaseMapLocationActivity<ActivityMonitorCarsBinding>(ActivityMonitorCarsBinding::inflate) {

    //View Model
    private val mViewModel by viewModels<MultiMonitorViewModel>()

    //导航弹窗
    private val mNaviPopup by lazy { ChooseNaviPopup(this) }

    //图例弹窗
    private val mLegendPopup by lazy { LegendPopup(this) }

    //更多弹窗
    private val mMorePopup by lazy { MapMorePopup(this) }

    //卡片弹窗
    private val mCarsPopup by lazy {
        CarsPopup(this).apply {
            setOnDismissListener {
                mViewModel.setShowCard(false)
                binding.tvList.visibility = View.VISIBLE
            }
            setCallBack(object : CarsPopup.CallBack {
                override fun callback(carId: String) {
                    mViewModel.carId = carId
                    mViewModel.nowCar()
                    isShowPopup = true
                    mViewModel.isOneCar = true
                    dismiss()
                }
            })
        }
    }

    // 时间弹窗
    private val mTimePopup by lazy {
        MapTimePopup(this, object : MapTimePopup.OnTimeCallBack {
            override fun onBack(time: Int) {
                mViewModel.saveRefresh(time)
            }
        })
    }

    //是否加载
    private var isLoaded = false

    //是否展示弹窗
    private var isShowPopup = false

    //当前车辆位置
    private var carLatLng: LatLng? = null

    //定位Marker
    private var mLocationMarker: Marker? = null

    //聚合类
    private val mOverlay by lazy {
        ClusterOverlay(
            mAMap, ScreenUtil.dp2px(this, 30), this
        )
    }

    private lateinit var mOperaVB: IncludeCarOperaBinding
    private lateinit var mInfoVB: IncludeCarMapInfoBinding

    //初始化地图
    override fun initMap() {
        mAMap.mapType = mViewModel.mapType
        mAMap.isTrafficEnabled = mViewModel.isTraffic
        MapUtil.initMapSetting(mAMap)

        mAMap.setInfoWindowAdapter(object : AMap.InfoWindowAdapter {
            override fun getInfoWindow(p0: Marker?): View? {
                val textView = TextView(this@MultiMonitorActivity)
                textView.text = getString(R.string.desc_location_now)
                textView.gravity = Gravity.CENTER

                return textView
            }

            override fun getInfoContents(p0: Marker?): View? {
                return null
            }
        })

        mAMap.setOnMarkerClickListener {
            return@setOnMarkerClickListener true
        }
        initOverlay()
        mMorePopup.setCluster(true)
    }

    override fun initView() {
        mOperaVB = IncludeCarOperaBinding.bind(binding.root)
        mInfoVB = IncludeCarMapInfoBinding.bind(binding.root)
        type = 1
        immersionBar { titleBar(binding.llToolbarCars) }

        binding.ivCarsTraffic.isSelected = mViewModel.isTraffic
        if (mViewModel.mapType == AMap.MAP_TYPE_NORMAL) {
            binding.tvCarsMapState.setText(R.string.desc_com_map_state_normal)
        } else {
            binding.tvCarsMapState.setText(R.string.desc_com_map_state_satellite)
        }
        if (mViewModel.isCarName) {
            binding.tvCarsState.setText(R.string.desc_car_name)
        } else {
            binding.tvCarsState.setText(R.string.desc_car_plate)
        }

        mMorePopup.setViewClickListener(moreListener)

        infoView()
        infoEvent()
        initViewModel()

        when {
            UserConstant.current_car_num == 0 -> {
                toast(R.string.desc_car_no_location_car)
            }

            UserConstant.current_car_num <= 300 -> {
                mViewModel.getAllCars()
                binding.tvList.visibility = View.VISIBLE
                binding.tvCarsTitle.text =
                    "${getString(R.string.desc_map_all_car)}  (${UserConstant.current_car_num})"
            }

            else -> {
                chooseTeam()
            }
        }
        if (mViewModel.isShowPopup) {
            binding.tvCarsMore.postDelayed(400) { mMorePopup.showAsDropDown(binding.tvCarsMore) }
        }
    }

    //设置ViewModel
    private fun initViewModel() {
        mViewModel.toastObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe(::toastObserver)
        //单车定位
        mViewModel.locationObserver().autoDispose(scopeProvider).subscribe {
            if (it) {
                isLoaded = true
                mViewModel.gpsDetail?.run {
                    carLatLng = LatLng(glat.toDouble(), glng.toDouble())
                    if (isShowPopup) {
                        initInfo()
                        mInfoVB.llCarInfo.visibility = View.VISIBLE
                        MapUtil.showLatLngZoom(mAMap, carLatLng!!)
                    }
                    mOverlay.removeSingleMarker(
                        ClusterItem(
                            carLatLng!!, carId, carName, carPlate,
                            iconLink, speed, state, drct
                        )
                    )
                    mOperaVB.rlCarsOperate.visibility = View.VISIBLE
                    binding.tvAround.visibility = View.VISIBLE
                }
            }
        }

        //图例
        mViewModel.legendObserver().autoDispose(scopeProvider).subscribe {
            mLegendPopup.showAtLocation(mOperaVB.ivCarsLegend, it)
        }

        //聚合
        mViewModel.clustersObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe {

                isLoaded = true
                mOverlay.addClusterItems(it)
                if (mViewModel.isBounds) {
                    mMorePopup.setShowCluster(it.size < 300)
                    mViewModel.isBounds = false
                    MapUtil.showMapBounds(mAMap, mViewModel.getBounds())
                }

            }

        //卡片数据监听
        mViewModel.gpsObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe {
                mCarsPopup.refreshData(it)
                mCarsPopup.resetTabLayouts(mViewModel.typeNum)
            }
    }

    //设置监听事件
    override fun setListener() {
        //返回按键
        binding.ivToolbarStart.setOnClickListener {

            finish()
        }

        //分组
        binding.tvCarsTeam.setOnClickListener {
            chooseTeam()
        }

        //路况
        binding.ivCarsTraffic.setOnClickListener {
            mViewModel.saveTraffic()
            binding.ivCarsTraffic.isSelected = mViewModel.isTraffic
        }

        //地图切换
        binding.tvCarsMapState.setOnClickListener {
            if (mViewModel.mapType == AMap.MAP_TYPE_NORMAL) {
                mAMap.mapType = AMap.MAP_TYPE_SATELLITE
                mViewModel.saveMapType(AMap.MAP_TYPE_SATELLITE)
                binding.tvCarsMapState.setText(R.string.desc_com_map_state_satellite)
            } else {
                mAMap.mapType = AMap.MAP_TYPE_NORMAL
                mViewModel.saveMapType(AMap.MAP_TYPE_NORMAL)
                binding.tvCarsMapState.setText(R.string.desc_com_map_state_normal)
            }
        }

        //车名车牌切换
        binding.tvCarsState.setOnClickListener {
            if (mViewModel.isCarName) {
                mViewModel.saveCarName(false)
                binding.tvCarsState.setText(R.string.desc_car_plate)
            } else {
                mViewModel.saveCarName(true)
                binding.tvCarsState.setText(R.string.desc_car_name)
            }
            mOverlay.refresh()
        }

        //更多
        binding.tvCarsMore.setOnClickListener {
            mMorePopup.showAsDropDown(binding.tvCarsMore)
        }

        //全显
        binding.tvDisplayAll.setOnClickListener {
            mOperaVB.rlCarsOperate.visibility = View.GONE
            binding.tvAround.visibility = View.GONE
            mInfoVB.llCarInfo.visibility = View.GONE
            mViewModel.isOneCar = false

            MapUtil.showMapBounds(mAMap, mViewModel.getBounds())
        }

        //放大
        binding.ivMapZoomIn.setOnClickListener {
            mAMap.animateCamera(CameraUpdateFactory.zoomOut(), 600, null)
        }

        //缩小
        binding.ivMapZoomOut.setOnClickListener {
            mAMap.animateCamera(CameraUpdateFactory.zoomIn(), 600, null)
        }

        //卡片列表
        binding.tvList.setOnClickListener {
            binding.tvList.visibility = View.GONE
            mViewModel.setShowCard(true)
            mCarsPopup.show(window.decorView)
        }

        //周边
        binding.tvAround.clickThrottle().autoDispose(scopeProvider).subscribe {
            startActivityTo<CarAroundActivity>(this) {
                putExtra(Keys.INTENT_CAR_NAME, mViewModel.gpsDetail?.carPlate)
                putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
            }
        }

        //手机定位
        mOperaVB.ivCarsPhone.clickThrottle().autoDispose(scopeProvider).subscribe {
            getPermissions(false)
        }

        //当前车辆位置
        mOperaVB.ivCarsNow.setOnClickListener {
            isShowPopup = true
            mViewModel.nowCar()
        }

        //图例
        mOperaVB.ivCarsLegend.setOnClickListener {
            mViewModel.getLegend()
        }

        //上一辆
        mOperaVB.ivCarsPrevious.setOnClickListener {
            isShowPopup = true
            mViewModel.previous()
        }

        //下一辆
        mOperaVB.ivCarsNext.setOnClickListener {
            isShowPopup = true
            mViewModel.nextCar()
        }

    }

    //更多点击事件
    private val moreListener = View.OnClickListener {
        mMorePopup.dismiss()
        when (it.id) {
            R.id.tv_popup_all_cars -> {
                mViewModel.getAllCars()
                binding.tvList.visibility = View.VISIBLE
            }
            R.id.tv_popup_clear_all -> {
                isLoaded = false
                mViewModel.stopTime()
                mAMap.clear()
                mOverlay.clearCluster()
                mViewModel.teamId = ""
                binding.tvList.visibility = View.GONE
                mOperaVB.rlCarsOperate.visibility = View.GONE
                binding.tvAround.visibility = View.GONE

                binding.tvCarsTitle.setText(R.string.title_monitor_cars)
                mInfoVB.llCarInfo.visibility = View.GONE
            }
            R.id.tv_popup_cluster -> {
                val cluster = !mViewModel.isCluster
                mViewModel.saveCluster(cluster)
                mMorePopup.setCluster(cluster)
                mOverlay.setCluster(cluster)
            }
            R.id.tv_show_popup -> {
                mViewModel.saveShowPopup(!mViewModel.isShowPopup)
                mMorePopup.setPopupShow(mViewModel.isShowPopup)
            }
            R.id.tv_popup_refresh -> {
                mTimePopup.showPopup(window.decorView)
            }
        }
    }

    //选择车队
    private fun chooseTeam() {
        launcher.launchAct<ChooseTeamActivity>(this) {
            putExtra("isMap", true)
        }
    }

    //定位当前位置
    override fun onMyLocationChange(location: Location) {
        if (location.extras["errorCode"] != 0) {
            location.extras["errorInfo"]?.toastLong(this)
            return
        }
        isShowPopup = false
        mInfoVB.llCarInfo.visibility = View.GONE

        val latLng = LatLng(location.latitude, location.longitude)
        MapUtil.showMapBounds(
            mAMap, mViewModel.getBounds(carLatLng!!, latLng), 300
        )

        if (mLocationMarker == null) {
            mLocationMarker = MapUtil.addAndGetMarker(
                mAMap, latLng, R.mipmap.ic_phone_location
            )
        } else {
            mLocationMarker?.position = latLng
        }
    }

    /** 移除定位Marker */
    private fun clearLocationMarker() {
        mLocationMarker?.remove()
        mLocationMarker = null
    }

    private val launcher = registerResult { result ->
        if (result.resultCode != RESULT_OK) return@registerResult
        result.data?.let {
            isLoaded = false
            val teamId = it.getStringExtra(Keys.INTENT_TEAM_ID) ?: ""
            val teamName = it.getStringExtra(Keys.INTENT_TEAM_NAME) ?: ""
            val carsNum = it.getStringExtra(Keys.INTENT_TEAM_NUM) ?: ""
            clearMap()
            mViewModel.teamId = teamId
            mViewModel.startTime()
            mOperaVB.rlCarsOperate.visibility = View.GONE
            binding.tvAround.visibility = View.GONE
            binding.tvCarsTitle.text = "$teamName  (${carsNum})"
            binding.tvList.visibility = View.VISIBLE
            mViewModel.isBounds = true
        }
    }

    /** Clear map */
    private fun clearMap() {
        mViewModel.stopTime()
        mOverlay.clearCluster()
        binding.tvList.visibility = View.GONE
        mOperaVB.rlCarsOperate.visibility = View.GONE
        binding.tvAround.visibility = View.GONE
        mInfoVB.llCarInfo.visibility = View.GONE
        mViewModel.isOneCar = false
        clearLocationMarker()
    }

    //////////////////////////////////////////////////////////////////////////////////
    private var lruCache: LruCache<String, BitmapDescriptor?>? = null
    var maxMemory = (Runtime.getRuntime().maxMemory() / 10240).toInt()

    private fun initOverlay() {
        val bitmapDrawable = ContextCompat.getDrawable(this, R.drawable.bg_blue_yuan)
        //缓存
        lruCache = object : LruCache<String, BitmapDescriptor?>(maxMemory) {
            override fun entryRemoved(
                evicted: Boolean, key: String,
                oldValue: BitmapDescriptor, newValue: BitmapDescriptor?
            ) {
                super.entryRemoved(evicted, key, oldValue, newValue)
                oldValue.recycle()
            }
        }

        //聚合marker 设置图标
        mOverlay.setClusterRenderer(object : ClusterRender {

            override fun getDrawAble(clusterNum: Int): Drawable {
                return bitmapDrawable!!
            }

            override fun getBitmapDesc(item: ClusterItem): BitmapDescriptor {
                val key: String = if (item.name == item.plate) {
                    "${item.carId}${item.drct}${item.iconLink}${item.speed}"
                } else {
                    "${item.carId}${item.drct}${item.iconLink}${item.speed}${mViewModel.isCarName}"
                }

                var bitmapDescriptor = lruCache?.get(key)
                if (bitmapDescriptor == null) {
                    val markerView =
                        MarkerView(this@MultiMonitorActivity, MarkerSet.mMarkerSet)
                    markerView.setMarkerInfo(item, mViewModel.isCarName)
                    bitmapDescriptor = BitmapDescriptorFactory.fromView(markerView)
                    lruCache?.put(key, bitmapDescriptor)
                }
                return bitmapDescriptor!!
            }
        })

        //聚合marker 点击事件
        mOverlay.setOnClusterClickListener(object : ClusterClickListener {

            override fun onClick(marker: Marker?, clusterItems: List<ClusterItem>) {
                val builder = LatLngBounds.Builder()
                for ((position) in clusterItems) {
                    builder.include(position)
                }
                val latLngBounds = builder.build()
                MapUtil.showMapBounds(mAMap, latLngBounds)
            }

            override fun onItemClick(marker: Marker?, clusterItem: ClusterItem) {
                if (marker == mLocationMarker) {
                    marker?.showInfoWindow()
                } else {
                    isShowPopup = true
                    mViewModel.carId = clusterItem.carId
                    mViewModel.nowCar()
                }
            }
        })
    }

    //////////////////////////////////////////////////////////////////////////////
    private val runSpeed by lazy { getString(R.string.desc_run_speed) }
    private val dayMile by lazy { getString(R.string.desc_day_mile) }

    @SuppressLint("SetTextI18n")
    fun initInfo() {
        mViewModel.gpsDetail?.run {
            mInfoVB.tvPlateName.text = sub(if (mViewModel.isCarName) carName else carPlate, 14)
            mInfoVB.tvCarRunSpeed.text = "$speed km/h\n$runSpeed"
            mInfoVB.tvCarRunStop.text = runStopTime
            mInfoVB.tvCarDayMile.text = "$preMile km\n$dayMile"
            mInfoVB.tvCarTotalMile.text = "$mile km"
            mInfoVB.tvCarTime.text = "${getString(R.string.desc_location_time)}：$time"

            val colorCode: String = if (plateColorCode.isNullOrEmpty()) {
                NetDataUtil.getColorByName(plateColor)
            } else {
                plateColorCode!!
            }
            when (colorCode) {
                "6", "93", "224" -> {
                    mInfoVB.tvPlateName.setBackgroundResource(R.drawable.ic_color_plate_93)
                }
                "94", "225" -> {
                    mInfoVB.tvPlateName.setBackgroundResource(R.drawable.ic_color_plate_94)
                }
                else -> {
                    val colorDrawable = ColorDrawable()
                    colorDrawable.color = Color.parseColor(ColorUtil.getPlateColor(colorCode))
                    mInfoVB.tvPlateName.background = colorDrawable
                }
            }
            mInfoVB.tvPlateName.setTextColor(Color.parseColor(ColorUtil.getPlateTextColor(colorCode)))

            mInfoVB.tvCarPhoto.text =
                if (!UserConstant.isRealVideo || videos.isNullOrEmpty()) {
                    getString(R.string.desc_marker_photo)
                } else {
                    getString(R.string.desc_single_car_real_video)
                }
        }
        if (isShowRecycler) {
            showInfoRecycler()
        }

    }

    private val mInfoAdapter by lazy { CarInfoAdapter() }
    private fun infoView() {
        mInfoVB.recyclerCarInfo.layoutManager = LinearLayoutManager(this)
        mInfoVB.recyclerCarInfo.adapter = mInfoAdapter
        mInfoVB.ivCarShare.isVisible = !BuildConfigs.ISGOOGLE && BuildConfigs.ISCOMPANY
    }

    private fun showInfoRecycler() {
        mInfoAdapter.setList(LocationStatusModel.upData(mViewModel.gpsDetail))
    }

    //是否展示列表
    private var isShowRecycler = false

    /** 设置info点击事件 */
    private fun infoEvent() {
        LiveDataBus.get().with("upInfoState").observe(this) {
            if (mViewModel.carId.isNullOrEmpty()) return@observe
            mViewModel.nowCar()
        }

        mInfoVB.ivUpDown.setOnClickListener {
            isShowRecycler = !isShowRecycler
            if (isShowRecycler) {
                showInfoRecycler()
                mInfoVB.recyclerCarInfo.visibility = View.VISIBLE
            } else {
                mInfoVB.recyclerCarInfo.visibility = View.GONE
            }
        }

        mInfoVB.ivUp.setOnClickListener {
            isShowRecycler = !isShowRecycler
            mInfoVB.ivUp.isSelected = isShowRecycler
            if (isShowRecycler) {
                showInfoRecycler()
                mInfoVB.recyclerCarInfo.visibility = View.VISIBLE
            } else {
                mInfoVB.recyclerCarInfo.visibility = View.GONE
            }
        }

        mInfoVB.ivCarSet.setOnClickListener {
            startActivityTo<InfoSetActivity>(this)
        }

        mInfoVB.ivCarClose.setOnClickListener {
            isShowPopup = false
            mInfoVB.llCarInfo.visibility = View.GONE
        }

        mInfoVB.ivCarRefresh.setOnClickListener {
            if (isFastClick()) return@setOnClickListener
            mViewModel.refreshCar()
        }

        mInfoVB.tvCarHistory.setOnClickListener {
            startActivity(HistoryLineActivity::class.java, mViewModel.gpsDetail)
        }

        mInfoVB.tvCarPhoto.setOnClickListener {
            val videos = mViewModel.gpsDetail?.videos
            if (!UserConstant.isRealVideo || videos.isNullOrEmpty()) {
                startActivity(PhotosActivity::class.java, mViewModel.gpsDetail)
            } else
                startActivity(
                    Intent(this, RealVideoActivity::class.java)
                        .putExtra(Keys.INTENT_CAR_ID, mViewModel.gpsDetail?.carId)
                        .putExtra(Keys.INTENT_PLATE, mViewModel.gpsDetail?.carPlate)
                        .putExtra(Keys.INTENT_CAR_NAME, mViewModel.gpsDetail?.carName)
                        .putExtra(Keys.INTENT_CAR_VIDEOS, mViewModel.gpsDetail?.videos)
                )
        }

        mInfoVB.tvCarSingle.setOnClickListener {
            startActivity(SingleMonitorActivity::class.java, mViewModel.gpsDetail)
        }

        mInfoVB.tvCarInfo.setOnClickListener {
            mViewModel.stopTime()
            startActivityTo<CarInfoActivity>(this) {
                putExtra(Keys.INTENT_CAR_ID, mViewModel.carId)
            }
        }

        mInfoVB.tvCarNavi.setOnClickListener {
            mNaviPopup.showAtLocation(window.decorView, mViewModel.gpsDetail)
        }

        mInfoVB.tvCarCall.setOnClickListener {
            if (mViewModel.gpsDetail?.drvPhone.isNullOrEmpty()) {
                R.string.desc_no_phone.toast(this)
            } else {
                //跳转到拨号界面，同时传递电话号码
                val dialIntent =
                    Intent(
                        Intent.ACTION_DIAL,
                        Uri.parse("tel:${mViewModel.gpsDetail?.drvPhone}")
                    )
                startActivity(dialIntent)
            }
        }

//        mInfoVB.ivCarShare.setOnClickListener {
//            WxShareUtil.instance.init(applicationContext)
//            mViewModel.gpsDetail?.let {
//                wxViewModel.shareLocation(it.carPlate, it.carId)
//            }
//
//        }
    }

//    private val wxViewModel by viewModels<WxShareModel>()

    private fun startActivity(zClass: Class<*>, entity: GpsDetail?) {
        startActivity(
            Intent(this, zClass)
                .putExtra(Keys.INTENT_CAR_ID, entity?.carId)
                .putExtra(Keys.INTENT_PLATE, entity?.carPlate)
                .putExtra(Keys.INTENT_CAR_NAME, entity?.carName)
        )
    }


    override fun onDestroy() {
        super.onDestroy()
        clearMap()
        BitmapUtil.clearLruCache()
    }

    private var isPause = false
    override fun onResume() {
        super.onResume()
        if (isPause && isLoaded) {
            isPause = false
            mViewModel.startTime()
        }
    }

    override fun onPause() {
        super.onPause()
        mViewModel.stopTime()
        isPause = true
    }

}